using System;
using EnvDTE;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using EnvDTE80;

namespace TeamReview.Replay
{
	internal sealed class FirstSnippetInDocumentLink : ReplayLink
	{
	    public FirstSnippetInDocumentLink(DTE2 applicationObject) : base(applicationObject)
	    {
	    }

	    public override ReplayReceipt TryShowReplay(WorkItem workItem, DTE2 applicationObject)
        {
            ReplayReceipt receipt = new ReplayReceipt();

            string fileName = AbsoluteCodeFilePath(workItem);
            object snippetObject = workItem.Fields[Constants.CODE_SNIPPET_FIELD].Value;

            if (String.IsNullOrEmpty(fileName) || !System.IO.File.Exists(fileName) || snippetObject == null)
                return receipt;

            string snippet = snippetObject.ToString();

			// lyubobg 22 December 2012 - Fixing issue 10149
			// Can not reopen javascript files
			// http://teamreview.codeplex.com/workitem/10149
			//EnvDTE.Document document = applicationObject.Documents.Open(fileName, "Auto", false);
			EnvDTE.Document document = null;
			applicationObject.ItemOperations.OpenFile(fileName);

			foreach (EnvDTE.Document tempDoc in applicationObject.Documents)
			{
				if (tempDoc.FullName == fileName)
				{
					document = tempDoc;
					break;
				}
			}
			// End of fix for 10149

            if (document == null)
                return receipt;

            EnvDTE.TextDocument td = (EnvDTE.TextDocument) document.Object("");

            if (td == null || td.Selection == null)
                return receipt;

            receipt.Selection = td.Selection;
            receipt.Selection.GotoLine(td.StartPoint.Line, false);
            EnvDTE.EditPoint startPoint = td.CreateEditPoint(receipt.Selection.ActivePoint);
            receipt.Selection.GotoLine(td.EndPoint.Line, true);
            EnvDTE.EditPoint endPoint = td.CreateEditPoint(receipt.Selection.ActivePoint);
            receipt.Selection.MoveToPoint(startPoint, false);
            receipt.Selection.MoveToPoint(endPoint, true);

            FindCodeSnippet(receipt, snippet,
                            String.Format(
                                "First occurrence of code snippet found in the document. Exact code could not be found at original line numbers."));
            HighlightCodeSnippet(receipt);

            return receipt;
        }
	}
}
